import os, sys, cv2, traceback
import numpy as np

parent_path = os.path.abspath(os.path.join(__file__, *([".."] * 3)))
sys.path.insert(0, parent_path)

import time, threading, yaml, json
from flask import Flask, request
from gevent import pywsgi, monkey, pool

from core.task.task_pipeline import TaskPipeline
from core.server import Server as BaseServer
from core.utils.logger import logging
# from projects.GangHang.processors.esdk import esdk

# 打补丁，使得标准库中的阻塞式I/O操作变为非阻塞式
# monkey.patch_all()

app = Flask(__name__)


class Server(BaseServer):
    def __init__(self, server_cfg_path: str) -> None:
        super().__init__(server_cfg_path)

    def line_task(self):
        pass


# ------ 系统相关api ------


@app.route("/api/option/restart", methods=["get"])
def handle_restart():
    try:
        server.restart()
        return {"code": 200}
    except Exception as e:
        logging.error(traceback.format_exc())


# ------ 功能api ------


@app.route("/detect", methods=["post"])
def handle_detect():
    try:
        databox = {}
        try:
            code = 200
            message = ""
            logging.info(f"|detect|")
            json_data = request.json

            # 加载任务还是取消任务
            # if json_data["data"]["data"]["tag"] == "pop":
            #     esdk.StopH264Stream()
            # else:
            #     esdk.StartH264Stream()

            logging.info(f"task : {json_data}")

            databox = server.main_request(data=json_data)
        except Exception as e:
            code = 500
            message = str(e)
            # message = traceback.format_exc()
            logging.error(message)

        response = {
            "code": code,
            "message": message,
            "data": databox["objects"] if databox.get("objects", False) else [],
            "flightid" : json_data["id"],
        }

        response = json.dumps(response, ensure_ascii=False)
        return response
    except Exception as e:
        code = 500
        message = traceback.format_exc()
        logging.error(message)


if __name__ == "__main__":
    # 日志初始化
    log_path = os.path.join(os.path.dirname(__file__), "configs/log_cfg.yaml")
    logging.set_config(log_path)

    # 定义后台服务类
    server_cfg_path = os.path.join(os.path.dirname(__file__), "configs/server_cfg.yaml")
    server = Server(server_cfg_path)

    # http 接口初始化
    # http_message_cfg_path = os.path.join(
    #     os.path.dirname(__file__), "configs/http_message_cfg.yaml"
    # )
    # http_message.init_cfg(http_message_cfg_path)

    # 启动机场 esdk 服务
    # print(esdk)
    # print(dir(esdk))

    # flag = esdk.Init()
    # print(flag)

    WSGI_server = pywsgi.WSGIServer(
        ("0.0.0.0", 2682),
        app,
        # spawn=pool.Pool()
    )
    logging.info("|server start|")
    WSGI_server.serve_forever()
    logging.info("|server stop|")
